﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.Move
{
    public partial class FrmProductionPrepare : Form
    {
        #region 变量
        bool flag = false;
        bool result = false;
        bool check_doc = false;
        DataTable dt_SfcNo = new DataTable();
        bool isSMT = false;
        string doc_no = string.Empty;//单据号
        DataTable _dt_ReserchMaterial = new DataTable();//可备料的物料
        string line = string.Empty;//线别
        string wocode = string.Empty;//工单
        string sfcno = string.Empty;//制令单
        string PCB_Material = string.Empty;//SMT段的PCB料号
        /// <summary>
        /// 是否进入替代料发料模式
        /// </summary>
        bool isReplace = false;
        #endregion
        #region 构造
        public FrmProductionPrepare()
        {
            InitializeComponent();
            databind();
        }
        #endregion
        #region 绑定制令单
        private void databind()
        {
            string strSql = string.Format(@"SELECT SfcNo FROM SfcDatProduct WHERE Status not in (5,6,7) and isenable='Y' ORDER BY PlanStart DESC");
            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            DataRow dr = dt.NewRow();
            dr["SfcNo"] = string.Empty;
            dr["SfcNo"] = string.Empty;
            dt.Rows.InsertAt(dr, 0);
            cbo_sfcNo.DisplayMember = "SfcNo";
            cbo_sfcNo.ValueMember = "SfcNo";
            cbo_sfcNo.DataSource = dt;

        }
        #endregion
        #region 输入物料SN
        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                if (txt_reelid.Text.Trim() == string.Empty)
                {
                    lbl_msg.Text = "物料条码不能为空.";
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                //ClearControl();
                lbl_msg.Text = string.Empty;
                //if (!CheckDoc())//校验备料单
                //{
                //    return;
                //}


                //校验物料SN是否在库并且可用
                string strSql = string.Format(@"SELECT Lock_Flag,Enable,MaterialCode,QTY,Storage_SN,DateCode,Version AS Ver  FROM dbo.T_Bllb_StockInfo_tbsi WHERE SerialNumber ='{0}'", txt_reelid.Text.Trim());
                DataTable dt_material = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_material.Rows.Count == 0)
                {
                    lbl_msg.Text = "物料条码不存在.";
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                string lock_flag = dt_material.Rows[0]["Lock_Flag"].ToString();//状态
                string error_text = string.Empty;
                switch (lock_flag)
                {
                    case "0":
                        break;
                    case "1":
                        error_text = "物料盘点中";
                        break;
                    case "2":
                        error_text = "物料冻结中";
                        break;
                    case "3":
                        error_text = "物料二次送检中";
                        break;
                    case "4":
                        error_text = "物料被报废";
                        break;
                    case "5":
                        error_text = "物料二检NG";
                        break;
                    case "6":
                        error_text = "物料备料中";
                        break;
                    case "7":
                        error_text = "物料已出库";
                        break;
                    case "8":
                        error_text = "物料被合盘";
                        break;
                    case "9":
                        error_text = "物料已出库，并冻结中";
                        break;
                    case "10":
                        error_text = "物料退料中";
                        break;
                    default:
                        error_text = "物料非可备料状态";
                        break;
                }
                if (error_text != string.Empty)
                {
                    lbl_msg.Text = error_text;
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
            

                //if (!isSMT)
                //{
                    strSql = string.Format(@"SELECT DISTINCT CASE WHEN QTY<Plan_Qty THEN 1 ELSE 0 END as qty
 FROM dbo.T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, dt_material.Rows[0]["MaterialCode"].ToString());
                    DataTable dt_CheckMaterial = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_CheckMaterial.Rows.Count == 0)
                    {
                        lbl_msg.Text = "物料不是" + sfcno + "所需要的.";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    else if (dt_CheckMaterial.Rows.Count == 1)
                    {
                        if (dt_CheckMaterial.Rows[0][0].ToString() == "0")
                        {
                            lbl_msg.Text = "物料" + dt_material.Rows[0]["MaterialCode"].ToString() + "已备齐.";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                    }
                //}
//                else
//                {
//                    strSql = string.Format(@"SELECT DISTINCT CASE WHEN QTY<PlanQty THEN 1 ELSE 0 END as qty
// FROM dbo.T_Bllb_StorageDocSMT_tbds WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, dt_material.Rows[0]["MaterialCode"].ToString());
//                    DataTable dt_CheckMaterial = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
//                    if (dt_CheckMaterial.Rows.Count == 0)
//                    {
//                        lbl_msg.Text = "物料不是" + sfcno + "所需要的.";
//                        lbl_msg.ForeColor = Color.Red;
//                        txt_reelid.Text = string.Empty;
//                        ReserchMateirl();
//                        txt_reelid.Focus();
//                        return;
//                    }
//                    else if (dt_CheckMaterial.Rows.Count == 1)
//                    {
//                        if (dt_CheckMaterial.Rows[0][0].ToString() == "0")
//                        {
//                            lbl_msg.Text = "物料" + dt_material.Rows[0]["MaterialCode"].ToString() + "已备齐.";
//                            lbl_msg.ForeColor = Color.Red;
//                            txt_reelid.Text = string.Empty;
//                            txt_reelid.Focus();
//                            ReserchMateirl();
//                            return;
//                        }
//                    }
//                }
             

             
                if (_dt_ReserchMaterial.Columns.Count == 0)
                {
                    error_text = "未维护料站表或者工单BOM";
                    lbl_msg.Text = error_text;
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                    return;
                }
                bool b_EmptyVer = true;//是否只有一条这个物料
                bool b_Need_ver = false;//是否校验版本
                string str_Need_Ver = string.Empty;//需要的物料版本
                string Ver=string.Empty;
                DataRow[] drs_ver = _dt_ReserchMaterial.Select(string.Format("MaterialCode='{0}'", SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"])));
                if (drs_ver.Length > 0)
                {
                    foreach (DataRow dr in drs_ver)
                    {
                        if (SqlInput.ChangeNullToString(dr["Ver"]) == string.Empty)//判断是否有这个版本的物料需要发，库存物料都是有版本号
                        {
                            b_EmptyVer = true;
                            break;
                        }
                        else if (SqlInput.ChangeNullToString(dr["Ver"]) == SqlInput.ChangeNullToString(dt_material.Rows[0]["Ver"]))//有相同版本的物料
                        {
                            b_Need_ver = true;
                            Ver=SqlInput.ChangeNullToString(dr["Ver"]) ;
                        }
                        else//需要的物料版本
                        {
                            str_Need_Ver += "[" + SqlInput.ChangeNullToString(dr["Ver"]) + "]";
                        }
                    }
                }
                if (!b_EmptyVer & !b_Need_ver & str_Need_Ver!=string.Empty)//判断物料的版本不是所需要的版本
                {
                    lbl_msg.Text = "备料单中此物料所需的版本为" + str_Need_Ver;
                    lbl_msg.ForeColor = Color.Red;
                    txt_reelid.Text = string.Empty;
                    txt_reelid.Focus();
                    ReserchMateirl();//重新获取可备物料
                    return;
                }
                else if(b_EmptyVer&!b_Need_ver)//存在版本为空的情况，并且当前物料不是所需要的特定版本物料
                {
                  Ver=string.Empty;
                }

                #region 判断datecode不同值数量
                DataView dataView = _dt_ReserchMaterial.DefaultView;
                DataTable dataTableDistinct = dataView.ToTable(true, "MaterialCode", "DateCode", "QTY","Ver");
                string maxDateCode = dataTableDistinct.Compute("max(DateCode)", string.Format(@"MaterialCode='{0}' and Ver='{1}'", SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"]),Ver)).ToString();
                string minDateCode = dataTableDistinct.Compute("min(DateCode)", string.Format(@"MaterialCode='{0}' and Ver='{1}'", SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"]),Ver)).ToString();

                string maxQTY = dataTableDistinct.Compute("max(QTY)", string.Format(@"MaterialCode='{0}' and Ver='{1}'", SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"]), Ver)).ToString();
                string minQTY = dataTableDistinct.Compute("min(QTY)", string.Format(@"MaterialCode='{0}' and Ver='{1}'", SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"]), Ver)).ToString();

                DataRow[] drs_Distinct = dataTableDistinct.Select(string.Format(@"MaterialCode='{0}' and Ver='{1}'", SqlInput.ChangeNullToString(dt_material.Rows[0]["MaterialCode"]), Ver));
                int distinct_length = drs_Distinct.Length;

                DataRow[] drs = _dt_ReserchMaterial.Select(string.Format(@"SerialNumber='{0}'", txt_reelid.Text.Trim()));
         
                
                //1、尾数盘指定物料SN,并且优先获取
                //if (maxDateCode != minDateCode)//DATECODE不同
                //{
                //    if (drs.Length == 0)
                //    {
                //        lbl_msg.Text = "当前物料不在备选物料中";
                //        lbl_msg.ForeColor = Color.Red;
                //        return;
                //    }
                //}

         
                if (SqlInput.ChangeNullToInt(dt_material.Rows[0]["DateCode"],0) != SqlInput.ChangeNullToInt(minDateCode,0))//物料SN不在范围中，判断datecode和数量是否与备选的物料一致
                {
                    lbl_msg.Text = SqlInput.ChangeNullToInt(dt_material.Rows[0]["DateCode"], 0) + "不符合DataCode优先，请选择DataCode为" + SqlInput.ChangeNullToInt(minDateCode, 0)+"物料";
                    //lbl_msg.Text = "请扫描datecode为"+minDateCode+"的物料";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                else if (maxQTY != minQTY)//判断是否所选的料盘中最小料盘和最大料盘是否一致，若不是，则先发最小料盘
                {
                    if (dt_material.Rows[0]["QTY"].ToString() == maxQTY)//若有尾盘，并且扫描的不是尾盘则提示
                    {
                        lbl_msg.Text = "不符合尾盘优先";
                        lbl_msg.ForeColor = Color.Red;
                        return;
                    }
                }

                #endregion

                //string doc_no = cbo_sfcNo.SelectedValue.ToString();//备料单
                string MaterialCode = dt_material.Rows[0]["MaterialCode"].ToString();//料号
                int qty = SqlInput.ChangeNullToInt(dt_material.Rows[0]["QTY"], 0);//数量         

                strSql = string.Empty;
                string TBDS_ID = string.Empty;
                string strSql_Sum = string.Empty;//SQL汇总
                if (!isSMT)//非SMT(BOM发料)
                {
                    strSql = string.Format(@"SELECT Plan_Qty,QTY,TSDM_ID FROM dbo.T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND MaterialCode='{1}' AND Ver='{2}'", doc_no, MaterialCode,Ver);
                    DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt.Rows.Count == 0)
                    {
                        if (Ver == string.Empty)
                            lbl_msg.Text = "备料单中不存在物料" + dt_material.Rows[0]["MaterialCode"].ToString();
                        else
                        {
                            lbl_msg.Text = "备料单中不存在版本为"+Ver+"物料" + dt_material.Rows[0]["MaterialCode"].ToString();
                        }
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty;
                        txt_reelid.Focus();
                        ReserchMateirl();//重新获取可备物料
                        return;
                    }
                    #region 非SMT
                    if (SqlInput.ChangeNullToInt(dt.Rows[0]["Plan_Qty"], 0) <= SqlInput.ChangeNullToInt(dt.Rows[0]["QTY"], 0))//备料数量是否已达到
                    {
                        lbl_msg.Text = "备料单中物料" + dt_material.Rows[0]["MaterialCode"].ToString() + "已备齐";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        ReserchMateirl();//重新获取可备物料
                        return;
                    }
                    #endregion
                }
                else//SMT料站表发料
                {
                    strSql = string.Format(@"SELECT Plan_Qty,QTY,TSDM_ID FROM dbo.T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, MaterialCode);
                    DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt.Rows.Count == 0)
                    {
                        lbl_msg.Text = "备料单中不存在物料" + dt_material.Rows[0]["MaterialCode"].ToString();
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty;
                        txt_reelid.Focus();
                        ReserchMateirl();//重新获取可备物料
                        return;
                    }

                    #region SMT
                    //if (!isReplace)//非替代料模式
                    //{
                        #region 非替代料
                        //获取T_Bllb_StorageDocSMT_tbds的TBDS_ID
                        strSql = string.Format(@"SELECT TBDS_ID FROM T_Bllb_StorageDocSMT_tbds WHERE S_DOC_NO='{0}' AND MATERIALCODE='{1}'  AND PLANQTY>QTY ORDER BY QTY ASC", doc_no, MaterialCode);
                        DataTable dt_TBDS_ID = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_TBDS_ID.Rows.Count == 0)
                        {
                            lbl_msg.Text = "物料" + MaterialCode + "已备齐";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            ReserchMateirl();//重新获取可备物料
                            txt_reelid.Focus();
                            return;
                        }
                        TBDS_ID = SqlInput.ChangeNullToString(dt_TBDS_ID.Rows[0]["TBDS_ID"]);
                        strSql_Sum = string.Format(@"UPDATE T_Bllb_StorageDocSMT_tbds SET QTY=QTY+{1} WHERE TBDS_ID='{0}'", TBDS_ID, qty);
                        #endregion
                    //}
                    //else
                    //{
                    //    #region 替代料
                    //    strSql = string.Format(@"SELECT TBDS_ID,MATERIALCODE FROM T_Bllb_StorageDocSMT_tbds WHERE S_DOC_NO='{0}' AND ReplaceMaterial like '%{1}%' AND PLANQTY>QTY ORDER BY QTY ASC", doc_no, MaterialCode);
                    //    DataTable dt_TBDS_ID = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    //    if (dt_TBDS_ID.Rows.Count == 0)
                    //    {
                    //        lbl_msg.Text = "物料" + MaterialCode + "已备齐";
                    //        lbl_msg.ForeColor = Color.Red;
                    //        txt_reelid.Text = string.Empty; ;
                    //        ReserchMateirl();//重新获取可备物料
                    //        txt_reelid.Focus();
                    //        return;
                    //    }
                    //    TBDS_ID = SqlInput.ChangeNullToString(dt_TBDS_ID.Rows[0]["TBDS_ID"]);
                    //    string old_MaterilCode = SqlInput.ChangeNullToString(dt_TBDS_ID.Rows[0]["MATERIALCODE"]);//被替代料的物料
                    //    strSql_Sum = string.Format(@" UPDATE T_Bllb_StorageDocSMT_tbds SET QTY=QTY+{1} WHERE TBDS_ID='{0}' ", TBDS_ID, qty);
                    //    strSql = string.Format(@" SELECT S_Doc_NO FROM dbo.T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, MaterialCode);
                    //    if (Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]).Rows.Count == 0)
                    //    {
                    //        strSql_Sum += string.Format(@" INSERT INTO T_Bllb_StorageDocMaterial_tsdm(S_Doc_NO,MaterialCode,QTY,Plan_Qty) VALUES('{0}','{1}',{2},{2}) ", doc_no, MaterialCode, qty);
                    //    }
                    //    else
                    //    {
                    //        strSql_Sum += string.Format(@" UPDATE T_Bllb_StorageDocMaterial_tsdm SET Plan_Qty=Plan_Qty+{2},QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'", doc_no, MaterialCode, qty);
                    //    }
                    //    //物料汇总数据中添加替代料汇总数据
                    //    //                        strSql_Sum += string.Format(@" 
                    //    //                                                        IF NOT EXISTS( SELECT S_Doc_NO FROM dbo.T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND MaterialCode='{1}')
                    //    //                                                        BEGIN
                    //    //                                                        INSERT INTO T_Bllb_StorageDocMaterial_tsdm(S_Doc_NO,MaterialCode,QTY,Plan_Qty)
                    //    //                                                        VALUES('{0}','{1}',{2},{2})
                    //    //                                                        END
                    //    //                                                        ELSE
                    //    //                                                        BEGIN
                    //    //                                                        UPDATE T_Bllb_StorageDocMaterial_tsdm SET Plan_Qty=Plan_Qty+{2},QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND MaterialCode='{1}'
                    //    //                                                        END
                    //    //                                                     ", doc_no, MaterialCode, qty);
                    //    //减少被替代料的计划数
                    //    strSql_Sum += string.Format(@" UPDATE T_Bllb_StorageDocMaterial_tsdm SET Plan_Qty=Plan_Qty-{2}  WHERE S_Doc_NO='{0}' AND MaterialCode='{1}' ", doc_no, MaterialCode, qty);
                    //    #endregion
                    //}


                    #endregion
                }
                #region 单据处理
                strSql = string.Format(@"SELECT RowNumber,TSDM_ID FROM T_Bllb_StorageDocMaterial_tsdm WHERE S_DOC_NO='{0}' AND MATERIALCODE='{1}'  AND Plan_Qty>QTY AND VER='{2}' ORDER BY RowNumber ASC", doc_no, MaterialCode, Ver);
                DataTable dt_RowNumber = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_RowNumber.Rows.Count > 0)
                {
                    int rownumber=SqlInput.ChangeNullToInt(dt_RowNumber.Rows[0][0], 0);
                    if (rownumber != 0)
                        strSql_Sum += string.Format(@" UPDATE T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND RowNumber='{1}' AND MATERIALCODE='{3}'", doc_no, rownumber, qty, MaterialCode);
                    else
                        strSql_Sum += string.Format(@" UPDATE T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND MATERIALCODE='{1}'", doc_no, MaterialCode, qty);
                }              
                strSql_Sum += string.Format(@" INSERT INTO dbo.T_Bllb_StorageDocDetail_tbsdd
                                                ( S_Doc_NO ,
                                                  MaterialCode ,
                                                  QTY ,
                                                  Create_Time ,
                                                  Creator ,
                                                  SerialNumber,TBDS_ID ,TSDM_ID
                                                )
                                        VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                  '{1}' , -- MaterialCode - nvarchar(50)
                                                  {2} , -- QTY - int
                                                  GETDATE() , -- Create_Time - datetime
                                                  '{3}' , -- Creator - nvarchar(50)
                                                  '{4}',  -- SerialNumber - nvarchar(50)     
                                                  '{5}' ,'{6}'                                              
                                                )", doc_no, MaterialCode, qty, Utils.uContext.UserIDk__BackingField, txt_reelid.Text.Trim(), TBDS_ID, SqlInput.ChangeNullToString(dt_RowNumber.Rows[0]["TSDM_ID"]));
                //修改物料状态
                strSql_Sum += string.Format(@" UPDATE dbo.T_Bllb_StockInfo_tbsi SET Lock_Flag='6',SfcNo='{1}',Area_SN='',Location_SN='',TBS_ID='' WHERE SerialNumber='{0}'", txt_reelid.Text.Trim(), sfcno);
       
                //物料操作日志
                strSql_Sum += string.Format(@" INSERT INTO T_Bllb_MaterialLog_tbml(SerialNumber,CreateTime,OperateType,MaterialCode,QTY,Creator,Memo,SfcNo,PLCode)
VALUES('{0}',GETDATE(),'{1}','{2}','{3}','{4}','{5}','{6}','{7}')", txt_reelid.Text.Trim(), "生产备料", MaterialCode, qty, Utils.uContext.UserIDk__BackingField, "", sfcno, line);
                Utils.NMS.Exectransql(Utils.uContext, strSql_Sum, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                lbl_msg.Text = "备料成功";
                lbl_msg.ForeColor = Color.Green;
                lbl_LocationSN.Text = doc_no;
                ReserchMateirl();
                txt_reelid.Text = string.Empty; ;
                txt_reelid.Focus();
                #endregion

            }
        }
        #endregion
        #region 制令单变化时初始化显示信息
        private void cbo_PO_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearControl();
        }
        #endregion
        #region 清空控件
        private void ClearControl()
        {
            lbl_MaterialCode.Text = string.Empty;
            lbl_NextSerialNumber.Text = string.Empty;
            lbl_LocationSN.Text = string.Empty;
            lbl_msg.Text = string.Empty;
        }
        #endregion
        #region 校验制令单
        private void cbo_PO_LostFocus(object sender, EventArgs e)
        {
         
            if (CheckSfcNo())
            {
                if (CreateDoc())//创建发料单
                {
                    lbl_msg.Text = string.Empty;
                    ReserchMateirl();//获取要发的物料
                    if (lbl_msg.Text == string.Empty)
                    {
                        lbl_msg.Text = "制令单设置OK";
                        lbl_msg.ForeColor = Color.Green;
                        return;
                    }
                   
                }          
            }
        }
        #endregion
        #region  校验制令单
        /// <summary>
        /// 校验制令单
        /// </summary>
        /// <returns></returns>
        private bool CheckSfcNo()
        {
            if (cbo_sfcNo.SelectedValue == null)
            {
                return false;
            }
            if (cbo_sfcNo.SelectedValue.ToString() == string.Empty)
            {
                lbl_msg.Text = "制令单不能为空";
                lbl_msg.ForeColor = Color.Red;
                return false;
            }
            string strSql = string.Format(@"SELECT WoCode,Line,Product,Status,BoardSide,BoradCnt,planqty,PCB_Material FROM dbo.SfcDatProduct WHERE SfcNo='{0}'", cbo_sfcNo.Text.Trim());
            dt_SfcNo = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt_SfcNo.Rows.Count == 0)
            {
                lbl_msg.Text = "制令单不存在";
                lbl_msg.ForeColor = Color.Red;
                return false;
            }
            else if (SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["Status"]) == "5" || SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["Status"]) == "6" || SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["Status"]) == "7")
            {
                lbl_msg.Text = "制令单不是可备料状态";
                lbl_msg.ForeColor = Color.Red;
                databind();
                return false;
            }
           
            return true;//搜索可备料的物料SN
        }
        #endregion
        #region 根据制令单自动创建发料单
        /// <summary>
        /// 根据制令单自动创建发料单
        /// </summary>
        /// <returns></returns>
        public bool CreateDoc()
        {
            string strSql = string.Empty;
            wocode = SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["WoCode"]);//工单
            sfcno = cbo_sfcNo.Text.Trim();//制令单
            line = SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["Line"]);//线别
            PCB_Material = SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["PCB_Material"]);//PCB料号
            string product = SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["Product"]);//产品代码
            string BoardSide = SqlInput.ChangeNullToString(dt_SfcNo.Rows[0]["BoardSide"]);//面别
            string ver = string.Empty;//版本
            int BoradCnt = SqlInput.ChangeNullToInt(dt_SfcNo.Rows[0]["BoradCnt"], 1);//拼版数
            int planqty = SqlInput.ChangeNullToInt(dt_SfcNo.Rows[0]["planqty"], 1);//计划数
            if (line.ToUpper().Contains("SMT"))//判断是否为SMT发料
            {
                //if (PCB_Material == string.Empty)
                //{
                //    lbl_msg.Text = "制令单中没有维护PCB料号";
                //    lbl_msg.ForeColor = Color.Red;
                //    return false;
                //}
                strSql = string.Format(@"SELECT TOP 1 S_Doc_NO FROM dbo.T_Bllb_StorageDoc_tbsd
WHERE SfcNo='{0}'  AND Close_Flag='N' AND S_DOC_TYPE='7' AND IsAutoCreate='Y' ORDER BY Create_Time desc", cbo_sfcNo.Text.Trim());
                DataTable dt_check = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_check.Rows.Count == 0)
                {
                    lbl_msg.Text = "请先进行发料单与料站表比对";
                    lbl_msg.ForeColor = Color.Red;
                    return false;
                }

                isSMT = true;
                strSql = string.Format(@"select top 1 ver from mdcdatSlot WHERE Line='{0}' AND Product='{1}' AND BoardSide='{2}' order by ver DESC", line, product, BoardSide);
                DataTable dt_ver = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_ver.Rows.Count == 0)
                {
                    lbl_msg.Text = "产品" + product + "在线别" + line + "未维护" + BoardSide + "料站表";
                    lbl_msg.ForeColor = Color.Red;
                    return false;
                }
                else
                {
                    ver = SqlInput.ChangeNullToString(dt_ver.Rows[0]["ver"]);//版本
                    if (ver == string.Empty)
                    {
                        ver = "0";
                    }
                }


            }
            else
            {
                isSMT = false;
            }
            strSql = string.Format(@"SELECT TOP 1 S_Doc_NO FROM dbo.T_Bllb_StorageDoc_tbsd
WHERE SfcNo='{0}'  AND Close_Flag='N' AND S_DOC_TYPE='7' AND IsAutoCreate='Y' ORDER BY Create_Time desc", cbo_sfcNo.Text.Trim());
            DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            bool isNew = true;//是否可以重新创建发料单，若是已经备料就不行
            if (dt_po.Rows.Count > 0 & !isSMT)//非SMT发料
            {
                doc_no = dt_po.Rows[0][0].ToString();
                strSql = string.Format(@"SELECT COUNT(1) FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}'", doc_no);
                DataTable dt_detailcount = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_detailcount.Rows[0][0].ToString() == "0")
                {
                    string strSqlDel = string.Format(@" DELETE FROM T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}'", doc_no);
                    strSqlDel += string.Format(@" DELETE FROM T_Bllb_StorageDocSMT_tbds WHERE S_Doc_NO='{0}'", doc_no);
                    strSqlDel += string.Format(@" DELETE FROM T_Bllb_StorageDoc_tbsd WHERE S_Doc_NO='{0}'", doc_no);
                    Utils.NMS.Exectransql(Utils.uContext, strSqlDel, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                }
                else
                {
                    isNew = false;
                }
            }
            if (isNew & !isSMT)
            {
              
                #region 单据头
                DataTable dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT TOP 1 RIGHT(S_Doc_NO,4)+1  FROM T_Bllb_StorageDoc_tbsd WHERE Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type='7' ORDER BY S_Doc_NO DESC"), new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_doc.Rows.Count > 0)
                {
                    doc_no = "FL" + DateTime.Now.ToString("yyMMdd") + SqlInput.ChangeNullToInt(dt_doc.Rows[0][0], 0).ToString("0000");
                }
                else
                {
                    doc_no = "FL" + DateTime.Now.ToString("yyMMdd") + "0001";
                }

                strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDoc_tbsd
                                                    ( S_Doc_NO ,
                                                      S_Doc_Type ,
                                                      Create_Time ,
                                                      Creator ,
                                                      SfcNo,
                                                      WoCode,
                                                      PLCode,
                                                      Before_Doc_No,
                                                      ProductCode,IsAutoCreate                                                     
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '7' , -- S_Doc_Type - nvarchar(10)
                                                      GETDATE() , -- Create_Time - datetime
                                                      '{1}' , -- Creator - nvarchar(50)
                                                      '{2}',  -- SfcNo - nvarchar(50)
                                                      '{3}',
                                                      '{4}',
                                                      '{5}',
                                                      '{6}','Y'
                                                         
                                                    )", doc_no, Utils.uContext.UserIDk__BackingField, sfcno, wocode, line, sfcno, product);
                #endregion
                //Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
//                if (isSMT)//SMT料站表发料
//                {
//                    #region SMT
//                    //添加PCB物料到发料单中
//                    strSql += string.Format(@"INSERT INTO [dbo].[T_Bllb_StorageDocMaterial_tsdm]
//           ([S_Doc_NO]
//           ,[MaterialCode]
//           ,[QTY] 
//           ,[Plan_Qty],RowNumber) VALUES('{0}','{1}',0,{2},1)
//", doc_no, PCB_Material, planqty);
//                    //添加料站表物料到发料单中
//                    strSql += string.Format(@"INSERT INTO [dbo].[T_Bllb_StorageDocMaterial_tsdm]
//           ([S_Doc_NO]
//           ,[MaterialCode]
//           ,[QTY] 
//           ,[Plan_Qty],RowNumber)
//select '{4}' , PartNumber,0,SUM(qty)*{5}/{6},ROW_NUMBER() OVER(ORDER BY PartNumber)+1 from mdcdatSlot 
//WHERE Product = '{0}' and Line ='{1}' and Ver='{2}' and BoardSide = '{3}'
// group by PartNumber
// ", product, line, ver, BoardSide, doc_no, planqty, BoradCnt);
//                    //添加PCB物料到发料单SMT表中
//                    strSql += string.Format(@"INSERT INTO [dbo].[T_Bllb_StorageDocSMT_tbds]
//           ([WoCode]
//           ,[SfcNo]
//           ,[Product]
//           ,[MaterialCode]
//           ,[PlanQty]
//           ,[Line]
//           ,[LaneNo]
//           ,[machineid]
//           ,[tableid]
//           ,[slot]
//           ,[side]
//           ,[Ver]
//           ,[FeederStep],BoardSide,S_Doc_NO)
//           VALUES
//           ('{0}','{1}','{2}','{3}',{4},'{5}','0','0','0','0','0',0,'','{6}','{7}')
//            ", wocode, sfcno, product, PCB_Material, planqty, line, BoardSide, doc_no);
//                    //添加料站表物料到发料单SMT表中，用于记录物料SN发到哪个站位
//                    strSql += string.Format(@"INSERT INTO [dbo].[T_Bllb_StorageDocSMT_tbds]
//           ([WoCode]
//           ,[SfcNo]
//           ,[Product]
//           ,[MaterialCode]
//           ,[PlanQty]
//           ,[Line]
//           ,[LaneNo]
//           ,[machineid]
//           ,[tableid]
//           ,[slot]
//           ,[side]
//           ,[Ver]
//           ,[FeederStep],BoardSide,S_Doc_NO,ReplaceMaterial)
//   SELECT '{4}' WoCode,'{5}' SfcNo,  Product,PartNumber,max(qty)*{6}/{7} qty,Line,LaneNo,machineid,tableid,
//slot,side,max(Ver) Ver,max(FeederStep) FeederStep,max(BoardSide) BoardSide,'{8}',max(ReplaceMaterial) ReplaceMaterial from mdcdatSlot 
//WHERE Product = '{0}' and Line ='{1}' and Ver='{2}' and BoardSide = '{3}'
// group by Product,PartNumber,Line,LaneNo,machineid,tableid,slot,side
//", product, line, ver, BoardSide, wocode, sfcno, planqty, BoradCnt, doc_no);
//                    Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
//                    #endregion
//                }
//                else//BOM发料
//                {
                    string strSqlCheck = string.Format(@"SELECT B.WoCode FROM dbo.T_Bllb_wocodeBom_tbwb A LEFT JOIN dbo.SfcDatProduct B ON B.WoCode = A.WoCode WHERE B.SfcNo='{0}'",sfcno);
                    DataTable dt_checkBom = Utils.NMS.QueryDataTable(Utils.uContext, strSqlCheck, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_checkBom.Rows.Count == 0)
                    {
                        lbl_msg.Text = "制令单未维护工单BOM";
                        lbl_msg.ForeColor = Color.Red;
                        return false;
                    }
                    #region BOM

//                    strSql += string.Format(@" INSERT INTO [dbo].[T_Bllb_StorageDocMaterial_tsdm]
//           ([S_Doc_NO]
//           ,[MaterialCode]
//           ,[QTY] 
//           ,[Plan_Qty],RowNumber)
//SELECT '{1}',B.MaterialCode,0, SUM(b.BOM_QTY*a.PlanQty),ROW_NUMBER() OVER(ORDER BY MaterialCode) 
// FROM dbo.SfcDatProduct A LEFT JOIN dbo.T_Bllb_wocodeBom_tbwb B 
// ON A.WoCode=B.WoCode WHERE A.SfcNo='{0}'
// GROUP BY b.MaterialCode,a.PlanQty ", sfcno, doc_no);
                    strSql += string.Format(@" INSERT INTO [dbo].[T_Bllb_StorageDocMaterial_tsdm]
           ([S_Doc_NO]
           ,[MaterialCode]
           ,[QTY] 
           ,[Plan_Qty],RowNumber,Ver)
SELECT '{1}',B.MaterialCode,0, SUM(b.BOM_QTY*a.PlanQty),ROW_NUMBER() OVER(ORDER BY MaterialCode) ,b.Ver
 FROM dbo.SfcDatProduct A LEFT JOIN dbo.T_Bllb_wocodeBom_tbwb B 
 ON A.WoCode=B.WoCode WHERE A.SfcNo='{0}'
 GROUP BY b.MaterialCode,a.PlanQty,b.Ver ", sfcno, doc_no);
                    Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    #endregion
                //}
            }
            else//已存在单据
            {
                doc_no = dt_po.Rows[0][0].ToString();
            }
            return true;
        }
        #endregion
        #region 获取可备料的物料SN
        /// <summary>
        /// 获取可备料的物料SN
        /// </summary>
        private bool ReserchMateirl()
        {

            if (isSMT)//SMT料站表发料
            {
                //SMT计算最小需要盘数
                string strSql = string.Format(@" SELECT COUNT(1) SUM_QTY,MATERIALCODE FROM T_Bllb_StorageDocMaterial_tsdm
 WHERE S_DOC_NO='{0}' AND Plan_Qty>Qty GROUP BY MATERIALCODE", doc_no);
                DataTable dt_SUM_QTY = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_SUM_QTY.Rows.Count > 0)
                {

                    //int SUM_QTY = SqlInput.ChangeNullToInt(dt_SUM_QTY.Rows[0]["SUM_QTY"], 0);
                    strSql = string.Empty;
                    string strUnion = string.Empty;
                    List<string> lst_material = new List<string>();
                    int M_Count = 1;
                    foreach (DataRow dr_package in dt_SUM_QTY.Rows)
                    {     
                        M_Count = SqlInput.ChangeNullToInt(dr_package["SUM_QTY"], 0);
                        //SMT获取库存中允许发送的物料SN
                        //在库位上的物料才能发料
                        if (strSql != string.Empty)
                        {
                            strUnion = " UNION ";
                        }
                        strSql += strUnion + string.Format(@"SELECT TOP {1}  A.SerialNumber,A.Location_SN,A.Area_SN,A.DateCode,A.MaterialCode,A.QTY,'{2}' Old_MaterialCode FROM dbo.T_Bllb_StockInfo_tbsi A 
INNER JOIN dbo.T_Bllb_StorageLocation_tbsl B ON A.Location_SN=B.Location_SN 
LEFT JOIN dbo.T_Bllb_Storage_tbs C ON A.Storage_SN=C.Storage_SN
WHERE A.MaterialCode='{0}' AND A.Lock_Flag='0' AND C.Storage_Type='1' ORDER BY A.DateCode ASC,A.QTY ASC,A.Location_SN ASC
", dr_package["MATERIALCODE"], M_Count, dr_package["MATERIALCODE"]);
                    }
                    strSql = "SELECT * FROM (" + strSql + ") M ORDER BY DateCode ASC,QTY ASC ";
                    //strSql = "SELECT * FROM (" + strSql + ") M ORDER BY M.Location_SN ASC";
                    _dt_ReserchMaterial = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);//获取可选备料的物料
                    strSql = string.Empty;
                    strUnion = string.Empty;
                    if (_dt_ReserchMaterial.Rows.Count == 0)//主料用完，替代料上
                    {
                        isReplace = false;//是否进入替代料发料模式
                        string msg = string.Empty;
                        foreach (DataRow dr in dt_SUM_QTY.Rows)
                        {
                            msg += dr["MATERIALCODE"].ToString() + Environment.NewLine;
                        }
                        lbl_LocationSN.Text = string.Empty;
                        lbl_MaterialCode.Text = string.Empty;
                        lbl_NextSerialNumber.Text = string.Empty;
                        lbl_msg.Text = "库存中物料不足" + Environment.NewLine + msg;
                        lbl_msg.ForeColor = Color.Red;
                        return false;
//                        foreach (DataRow dr_package in dt_SUM_QTY.Rows)
//                        {
//                            string str_replace = SqlInput.ChangeNullToString(dr_package["ReplaceMaterial"]);//替代料
//                            if (str_replace == string.Empty)
//                            {
//                                continue;
//                            }
//                            string[] lst_rms = str_replace.Replace("，", ",").Split(',');
//                            string where_ReplaceMaterial = string.Empty;
//                            foreach (string s in lst_rms)
//                            {
//                                //20180715 bug修改 Zach
//                                where_ReplaceMaterial += where_ReplaceMaterial == string.Empty ? "'" + s + "'" : ",'" + s + "'";
//                            }
//                            //SMT获取库存中允许发送的物料SN
//                            //在库位上的物料才能发料
//                            if (strSql != string.Empty)
//                            {
//                                strUnion = " UNION ";
//                            }
//                            strSql += strUnion + string.Format(@" SELECT TOP {1} A.SerialNumber,A.Location_SN,A.Area_SN,A.DateCode,A.MaterialCode,A.QTY,'{2}' Old_MaterialCode FROM dbo.T_Bllb_StockInfo_tbsi A 
//INNER JOIN dbo.T_Bllb_StorageLocation_tbsl B ON A.Location_SN=B.Location_SN 
//LEFT JOIN dbo.T_Bllb_Storage_tbs C ON A.Storage_SN=C.Storage_SN
//WHERE A.MaterialCode in ({0}) AND A.Lock_Flag='0'  AND C.Storage_Type='1'  ORDER BY A.DateCode ASC,A.QTY ASC,A.Location_SN ASC
// ", where_ReplaceMaterial, SUM_QTY, dr_package["MATERIALCODE"]);
//                        }
//                        if (string.IsNullOrEmpty(strSql))
//                        {
//                            string msg = string.Empty;
//                            foreach (DataRow dr in dt_SUM_QTY.Rows)
//                            {
//                                msg += dr["MATERIALCODE"].ToString()+Environment.NewLine;
//                            }

//                            lbl_msg.Text = "库存中物料不足"+Environment.NewLine+msg;
//                            lbl_msg.ForeColor = Color.Red;
//                            return false;
//                        }
//                        strSql = " SELECT * FROM (" + strSql + ") M ORDER BY Location_SN ASC ";
//                        _dt_ReserchMaterial = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);//获取可选备料的替代料
//                        if (_dt_ReserchMaterial.Rows.Count == 0)
//                        {
//                            string msg = string.Empty;
//                            foreach (DataRow dr in dt_SUM_QTY.Rows)
//                            {
//                                msg += dr["MATERIALCODE"].ToString() + Environment.NewLine;
//                            }

//                            lbl_msg.Text = "库存中物料不足" + Environment.NewLine + msg;
//                            lbl_msg.ForeColor = Color.Red;
//                            return false;
//                        }

//                        isReplace = true;//是否进入替代料发料模式
                    }
                    else
                    {
                        isReplace = false;//是否进入替代料发料模式
                    }


                }
                else
                {
                    lbl_LocationSN.Text = string.Empty;
                    lbl_MaterialCode.Text = string.Empty;
                    lbl_NextSerialNumber.Text = string.Empty;
                    lbl_msg.Text = "制令单备料完成";
                    lbl_msg.ForeColor = Color.Green;
                    return false;
                }
            }
            else//BOM发料
            {
                string strSql = string.Format(@"SELECT COUNT(1) AS SUM_QTY,B.MaterialCode,B.Ver FROM dbo.T_Bllb_StorageDoc_tbsd A LEFT JOIN dbo.T_Bllb_StorageDocMaterial_tsdm B ON A.S_Doc_NO=B.S_Doc_NO
WHERE A.SfcNo='{0}' AND B.QTY<B.Plan_Qty GROUP BY B.MaterialCode,B.Ver  ", sfcno);
                DataTable dt_BOM = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_BOM.Rows.Count == 0)
                {
                    lbl_LocationSN.Text = string.Empty;
                    lbl_MaterialCode.Text = string.Empty;
                    lbl_NextSerialNumber.Text = string.Empty;
                    lbl_msg.Text = "制令单备料完成";
                    lbl_msg.ForeColor = Color.Green;
                    return false;
                }
                strSql = string.Empty;
                //int SUM_QTY = SqlInput.ChangeNullToInt(dt_BOM.Rows[0]["SUM_QTY"], 0);
              
                string strUnion = string.Empty;
                string ver = string.Empty;
                List<string> lst_material = new List<string>();
                int M_Count = 1;
                foreach (DataRow dr_bom in dt_BOM.Rows)
                {
                    ver = SqlInput.ChangeNullToString(dr_bom["Ver"]).Trim();//物料版本
                    M_Count = SqlInput.ChangeNullToInt(dr_bom["SUM_QTY"], 0);
                    //获取库存中允许发送的物料SN
                    //在库位上的物料才能发料
                    if (strSql != string.Empty)
                    {
                        strUnion = " UNION ";
                    }
             
                    if (ver == string.Empty)
                    {
                        strSql += strUnion + string.Format(@" SELECT TOP {1} A.SerialNumber,A.Location_SN,A.Area_SN,A.DateCode,A.MaterialCode,A.QTY,'' AS Ver FROM dbo.T_Bllb_StockInfo_tbsi A INNER JOIN dbo.T_Bllb_StorageLocation_tbsl B ON A.Location_SN=B.Location_SN WHERE A.MaterialCode='{0}' AND A.Lock_Flag='0'  ORDER BY A.DateCode ASC,A.QTY ASC,A.Location_SN ASC
", dr_bom["MaterialCode"], M_Count);
                    }
                    else
                    {
                        strSql += strUnion + string.Format(@" SELECT TOP {1} A.SerialNumber,A.Location_SN,A.Area_SN,A.DateCode,A.MaterialCode,A.QTY,A.Version AS Ver FROM dbo.T_Bllb_StockInfo_tbsi A INNER JOIN dbo.T_Bllb_StorageLocation_tbsl B ON A.Location_SN=B.Location_SN WHERE A.MaterialCode='{0}' AND A.Lock_Flag='0' and Version='{2}'  ORDER BY A.DateCode ASC,A.QTY ASC,A.Location_SN ASC
", dr_bom["MaterialCode"], M_Count, ver);
                    }

                }
                if (string.IsNullOrEmpty(strSql))
                {
                    string msg = string.Empty;
                    foreach (DataRow dr in dt_BOM.Rows)
                    {
                        msg += dr["MATERIALCODE"].ToString() + (SqlInput.ChangeNullToString(dr["Ver"]) != string.Empty ? "*" + SqlInput.ChangeNullToString(dr["Ver"]) : "" + Environment.NewLine);
                    }
                    lbl_LocationSN.Text = string.Empty;
                    lbl_MaterialCode.Text = string.Empty;
                    lbl_NextSerialNumber.Text = string.Empty;
                    lbl_msg.Text = "库存中物料不足" + Environment.NewLine + msg;
                    lbl_msg.ForeColor = Color.Red;
                    return false;
                }
                strSql = " SELECT * FROM (" + strSql + ") M ORDER BY DateCode ASC,QTY ASC ";
                _dt_ReserchMaterial = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);//获取可选备料的物料
                if (_dt_ReserchMaterial.Rows.Count == 0)
                {
                    string msg = string.Empty;
                    foreach (DataRow dr in dt_BOM.Rows)
                    {
                        //msg += dr["MATERIALCODE"].ToString() + Environment.NewLine;
                        msg += dr["MATERIALCODE"].ToString() + (SqlInput.ChangeNullToString(dr["Ver"]) != string.Empty ? "*" + SqlInput.ChangeNullToString(dr["Ver"]) : "" + Environment.NewLine);
                    }
                    lbl_LocationSN.Text = string.Empty;
                    lbl_MaterialCode.Text = string.Empty;
                    lbl_NextSerialNumber.Text = string.Empty;
                    lbl_msg.Text = "库存中物料不足" + Environment.NewLine + msg;
                    lbl_msg.ForeColor = Color.Red;
                    return false;
                }
            }     
            lbl_NextSerialNumber.Text =  SqlInput.ChangeNullToString(_dt_ReserchMaterial.Rows[0]["SerialNumber"]);//物料SN
            lbl_MaterialCode.Text = SqlInput.ChangeNullToString(_dt_ReserchMaterial.Rows[0]["MaterialCode"]);//料号
            lbl_LocationSN.Text = SqlInput.ChangeNullToString(_dt_ReserchMaterial.Rows[0]["Location_SN"]);//库位
            return true;
        }


        #endregion

    }
}